package core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import persistence.TransactionManager;

/** This class will control the simple persistence for our core object model
 *  it will handle the loading from disk to memory and saving.
 */
public class DataManager {
	
	private static boolean databaseMode;
	
	/** added this so that stuff wont get saved or loaded if in Test Mode */
	private static boolean _testMode;
	
	/** Every time the program is opened this function will load the data
	 *  that was last used, the previous time it was run.
	 * @param fileName the name of file that we will load the object from
	 * @throws IOException
	 * @throws ClassNotFoundException 
	 */
	public static Object loadAtStart(String fileName) throws IOException, ClassNotFoundException
	{
		if (_testMode == true)
		{
			System.out.println("TestMode Don't load anything");
			return null;
		}
		
		assert(!fileName.isEmpty());
		TransactionManager.initialize();
		FileInputStream fileIn = new FileInputStream(fileName);
		ObjectInputStream in = new ObjectInputStream(fileIn);
		Object o = in.readObject();
		in.close();
		fileIn.close();
		return o;
	}
	
	/** This will save the data being used the program onto the disk so 
	 *  the data will be stored.
	 * 
	 * @param o object to save
	 * @param fileName name of the file where we will save it.
	 * @throws IOException
	 */
	public static void saveAtClose(Object o, String fileName) throws IOException
	{
		if (_testMode == true)
		{
			System.out.println("Test Mode Don't save anything");
			return;
		}
		
		assert(o != null);
		assert(!fileName.isEmpty());
		FileOutputStream fileOut = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(fileOut);
		out.writeObject(o);
		out.close();
		fileOut.close();
	}
	
	public static void setMode(boolean dbMode)
	{
		databaseMode = dbMode;
	}
	
	public static boolean isInDatabaseMode()
	{
		return databaseMode;
	}
	
	public static void setTestMode(boolean testMode)
	{
		_testMode = testMode;
		if (testMode == true)
		{
			databaseMode = false;
		}
	}

}
